package cn.mumzone.pos.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.mumzone.basic.adapter.rv.CommonAdapter;
import cn.mumzone.basic.adapter.rv.ViewHolder;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.MoneyFormatUtil;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.model.RepoGoodsEntity;
import cn.mumzone.pos.model.RepoGoodsSpecEntity;
import cn.mumzone.pos.model.RepoListGoodsEntity;
import cn.mumzone.pos.ui.widgets.keyboard.PosKeyBoardView;
import cn.mumzone.pos.ui.widgets.shopping.AnimShopButton;
import cn.mumzone.pos.ui.widgets.util.StringSpanUtils;
import cn.mumzone.pos.util.GoodsUtil;

/**
 * Created by qiuzhenhuan on 2019/7/31.
 * <p>
 * 出入库搜索结果列表适配器 && 列表展示，入库类型为「其他」时的适配器
 */

public class ADA_CustomStockIn extends CommonAdapter<RepoListGoodsEntity> {

    private Context context;
    private boolean canDelete;
    private LayoutInflater mInflater;

    public ADA_CustomStockIn(Context context, boolean canDelete) {
        super(context);
        this.context = context;
        this.canDelete = canDelete;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    protected int itemLayoutId() {
        return R.layout.item_custom_in_stock_list;
    }

    @Override
    protected void convert(final ViewHolder holder, final RepoListGoodsEntity repoGoodsEntity, final int position) {

        holder.setText(R.id.tv_good_name, StringUtils.get(repoGoodsEntity.getGoodsName()));
        holder.setText(R.id.tv_good_spec, getFormatGoodsSpec(repoGoodsEntity.getParameter()));

        if (canDelete) {
            // 盘点页面，可操作删除条目
            holder.setVisible(R.id.iv_delete, true);
            holder.setOnClickListener(R.id.iv_delete, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 点击删除以后
                    if (mListener != null) {
                        mListener.OnClicked(position - 1, repoGoodsEntity);
                    }
                }
            });
        } else {
            holder.setVisible(R.id.iv_delete, false);
        }

        final LinearLayout llSingle = holder.getView(R.id.ll_goods_info_layout);
        final TextView tvSinglePrice = holder.getView(R.id.tv_price);

        final LinearLayout llAddBatchLayout = holder.getView(R.id.ll_add_batch);
        final LinearLayout llBatchLayout = holder.getView(R.id.ll_batch_layout);
        final LinearLayout llDoAddBatch = holder.getView(R.id.ll_do_add_batch);

        // 如果有批次信息
        if (repoGoodsEntity.getIsBatch() == RepoListGoodsEntity.BATCH_ON) {
            llAddBatchLayout.setVisibility(View.VISIBLE);
            llSingle.setVisibility(View.GONE);
            tvSinglePrice.setVisibility(View.GONE);
            llBatchLayout.removeAllViews();

            for (int i = 0; i < repoGoodsEntity.getGoodsBatch().size(); i++) {
                final RepoGoodsEntity batchInfo = repoGoodsEntity.getGoodsBatch().get(i);

                // 如果不是手动添加的批次
                // 或者该批次虽然是手动添加，但是后来又将数量减到了 0，就也将它舍弃
                if (!batchInfo.isManuallyAdd() || batchInfo.getSelectedCount() == 0) {
                    continue;
                }

                View batchInfoItem = mInflater.inflate(R.layout.item_in_stock_add_batch, null);

                ImageView ivDelete = batchInfoItem.findViewById(R.id.iv_delete);

                TextView tvDate = batchInfoItem.findViewById(R.id.tv_production_date);
                tvDate.setText(String.format("生产日期：%s", batchInfo.getDateInProduced()));

                TextView tvBatchNum = batchInfoItem.findViewById(R.id.tv_batch_number);
                tvBatchNum.setText(String.format("批    次：%s", batchInfo.getGoodsBatchNumber()));

                final TextView tvPrice = batchInfoItem.findViewById(R.id.tv_price);
                tvPrice.setText(String.format("￥%s", batchInfo.getInStockPrice()));
                tvPrice.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showModifyPriceDialog(repoGoodsEntity, batchInfo, tvPrice);
                    }
                });

                batchInfoItem.findViewById(R.id.iv_go_right).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mOnModifyBatchListener != null) {
                            mOnModifyBatchListener.onModifyBatch(repoGoodsEntity, batchInfo);
                        }
                    }
                });
                View vContent = batchInfoItem.findViewById(R.id.v_item);
                vContent.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mOnModifyBatchListener != null) {
                            mOnModifyBatchListener.onModifyBatch(repoGoodsEntity, batchInfo);
                        }
                    }
                });

                final AnimShopButton shopButton = batchInfoItem.findViewById(R.id.v_modify_count);
                shopButton.setMinCount(canDelete ? 1 : 0);
                shopButton.setCount(batchInfo.getSelectedCount());

                final int tag = i;
                shopButton.setOnAddDelListener(new GoodsStockButtonAdapter(mContext) {
                    @Override
                    protected void onAmountChanged(int count) {
                        batchInfo.setSelectedCount(count);
                        if (mOnAmountChangeListener != null) {
                            mOnAmountChangeListener.onAmountChanged(count, tag, repoGoodsEntity);
                        }
                    }

                    @Override
                    public void onInputAreaClicked() {
                        super.onInputAreaClicked();
                        GoodsUtil.showModifyCountDialog(mContext, new PosKeyBoardView.OnConfirmClickListener() {
                            @Override
                            public void onConfirmClick(String text) {
//                                batchInfo.setSelectedCount(Integer.parseInt(text));
//                                notifyItemChanged(position - 1);

                                int inputCount = Integer.parseInt(text);
                                if (inputCount > 0) {
                                    batchInfo.setSelectedCount(inputCount);
                                }
                                shopButton.setCount(inputCount);
                                shopButton.invalidate();

                                if (mOnAmountChangeListener != null) {
                                    mOnAmountChangeListener.onAmountChanged(Integer.parseInt(text), tag, repoGoodsEntity);
                                }
                            }
                        });
                    }
                });

                if (!canDelete) {
                    ivDelete.setVisibility(View.GONE);
                } else {
                    ivDelete.setVisibility(View.VISIBLE);
                    ivDelete.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            if (mOnBatchDeleteClickedListener != null) {
                                mOnBatchDeleteClickedListener.onBatchDeleted(repoGoodsEntity, batchInfo);
                            }

                        }
                    });
                }

                llBatchLayout.addView(batchInfoItem);

            }

            // 添加批次按钮，点击后新建批次
            llDoAddBatch.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnModifyBatchListener != null) {
                        mOnModifyBatchListener.onModifyBatch(repoGoodsEntity, null);
                    }
                }
            });


        } else {
            llSingle.setVisibility(View.VISIBLE);
            tvSinglePrice.setVisibility(View.VISIBLE);
            llAddBatchLayout.setVisibility(View.GONE);

            final RepoGoodsEntity batchInfo = repoGoodsEntity.getGoodsBatch().get(0);
            tvSinglePrice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showModifyPriceDialog(repoGoodsEntity, batchInfo, tvSinglePrice);
                }
            });
            tvSinglePrice.setText(String.format("￥%s", batchInfo.getInStockPrice()));

            final AnimShopButton shopButton = holder.getView(R.id.v_modify_count);
            shopButton.setMinCount(canDelete ? 1 : 0);
            shopButton.setCount(repoGoodsEntity.getSelectedCount());
            shopButton.setOnAddDelListener(new GoodsStockButtonAdapter(mContext) {
                @Override
                protected void onAmountChanged(int count) {
                    repoGoodsEntity.setSelectedCount(count);
                    if (mOnAmountChangeListener != null) {
                        mOnAmountChangeListener.onAmountChanged(count, -1, repoGoodsEntity);
                    }
                }

                @Override
                public void onInputAreaClicked() {
                    super.onInputAreaClicked();
                    GoodsUtil.showModifyCountDialog(mContext, new PosKeyBoardView.OnConfirmClickListener() {
                        @Override
                        public void onConfirmClick(String text) {
//                            repoGoodsEntity.setSelectedCount(Integer.parseInt(text));
//                            notifyItemChanged(position - 1);

                            int inputCount = Integer.parseInt(text);
                            if (inputCount > 0) {
                                repoGoodsEntity.setSelectedCount(inputCount);
                            }
                            shopButton.setCount(inputCount);
//                            shopButton.invalidate();

                            if (mOnAmountChangeListener != null) {
                                mOnAmountChangeListener.onAmountChanged(inputCount, -1, repoGoodsEntity);
                            }
                        }
                    });
                }
            });

        }

    }

    private String getFormatGoodsSpec(List<RepoGoodsSpecEntity> goodsSpec) {
        StringBuilder builder = new StringBuilder();
        if (!ListUtil.isListEmpty(goodsSpec)) {
            for (int index = 0; index < goodsSpec.size(); index++) {
                RepoGoodsSpecEntity specBean = goodsSpec.get(index);
                builder.append(specBean.getParamValue());
                if (index < goodsSpec.size() - 1) {
                    builder.append("，");
                }
            }
        }
        return StringSpanUtils.init().addForegroundColorHighLight(mContext.getResources().getColor(R.color.weak_text_color), "规格：")
                .addStr(StringUtils.get(builder.toString(), "无")).build().toString();
    }

    private void showModifyPriceDialog(final RepoListGoodsEntity repoGoodsEntity, final RepoGoodsEntity batchInfo, final TextView tvPrice) {
        final AlertDialog modifyPriceDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_modify_in_stock_price)
                .setDialogTitle("修改入库单价")
                .setDialogNoConfirm()
                .setWidthAndHeight(438, 467)
                .show();
        PosKeyBoardView kbPrice = modifyPriceDialog.findViewById(R.id.kb_price);
        final EditText etPrice = modifyPriceDialog.findViewById(R.id.et_price);
        MoneyFormatUtil.setTextFilter(etPrice);
        kbPrice.attachTo(etPrice);
        etPrice.setFocusable(false);
        etPrice.setHint(tvPrice.getText().toString().substring(1));
        kbPrice.setOnConfirmClickListener(new PosKeyBoardView.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String text) {
                tvPrice.setText(String.format("￥%s", text));
                batchInfo.setInStockPrice(Double.parseDouble(text));
                modifyPriceDialog.dismiss();
                if (mOnModifyPriceListener != null) {
                    mOnModifyPriceListener.onModifyPrice(repoGoodsEntity);
                }
            }
        });
    }

    public int getSelectedCount() {
        int totalCount = 0;
        outer: for (RepoListGoodsEntity entity : getDataList()) {
            if (entity.getIsBatch() == RepoListGoodsEntity.BATCH_ON) {
                for (RepoGoodsEntity batchEntity : entity.getGoodsBatch()) {
                    if (batchEntity.getSelectedCount() > 0) {
                        totalCount += 1;
                        continue outer;
                    }
                }
            } else {
                if (entity.getSelectedCount() > 0) {
                    totalCount += 1;
                }
            }
        }
        return totalCount;
    }

    public List<RepoListGoodsEntity> getSelectedData() {
        ArrayList<RepoListGoodsEntity> selectedList = new ArrayList<>();
        List<RepoListGoodsEntity> dataList = getDataList();
        outer: for (RepoListGoodsEntity entity : dataList) {
            if (entity.getIsBatch() == RepoListGoodsEntity.BATCH_ON) {
                for (RepoGoodsEntity batchEntity : entity.getGoodsBatch()) {
                    if (batchEntity.getSelectedCount() > 0) {
                        selectedList.add(entity);
                        continue outer;
                    }
                }
            } else {
                if (entity.getSelectedCount() > 0) {
                    selectedList.add(entity);
                }
            }
        }
        return selectedList;
    }

    // 条目删除的回调
    public interface OnItemDeleteClickedListener {
        void OnClicked(int position, RepoListGoodsEntity repoGoodsEntity);
    }

    private OnItemDeleteClickedListener mListener;

    public void setOnItemDeleteClickedListener(OnItemDeleteClickedListener mListener) {
        this.mListener = mListener;
    }


    // 批次删除的回调
    public interface OnBatchDeleteClickedListener {
        void onBatchDeleted(RepoListGoodsEntity currEntity, RepoGoodsEntity currBatch);
    }

    private OnBatchDeleteClickedListener mOnBatchDeleteClickedListener;

    public void setOnBatchDeletedListener(OnBatchDeleteClickedListener mListener) {
        this.mOnBatchDeleteClickedListener = mListener;
    }


    // 数量变化的回调 单批次&多批次共用
    public interface OnAmountChangeListener {
        void onAmountChanged(int count, int tag, RepoListGoodsEntity currEntity);
    }

    private OnAmountChangeListener mOnAmountChangeListener;

    public void setOnAmountChangeListener(OnAmountChangeListener mListener) {
        this.mOnAmountChangeListener = mListener;
    }


    // 编辑批次的回调
    public interface OnModifyBatchListener {
        void onModifyBatch(RepoListGoodsEntity currEntity, RepoGoodsEntity batchInfo);
    }

    private OnModifyBatchListener mOnModifyBatchListener;

    public void setOnModifyBatchListener(OnModifyBatchListener mListener) {
        this.mOnModifyBatchListener = mListener;
    }

    // 编辑单批次商品价格的回调
    public interface OnModifyPriceListener {
        void onModifyPrice(RepoListGoodsEntity currEntity);
    }

    private OnModifyPriceListener mOnModifyPriceListener;

    public void setOnModifyPriceListener(OnModifyPriceListener mListener) {
        this.mOnModifyPriceListener = mListener;
    }
}
